/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.web.controllers;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.app.model.entities.JmbPostTags;
import org.app.model.entities.JmbUserPosts;
import org.app.model.session.JmbPostTagsFacade;
import org.app.model.session.JmbUserPostsFacade;

/**
 *
 * @author Santiago
 */
@ManagedBean
@RequestScoped
public class SearchBeanController {
  @EJB
  private JmbPostTagsFacade jmbPostTagsFacade;
  @EJB
  private JmbUserPostsFacade jmbUserPostsFacade;
  private String postQ;

  
  /**
   * Creates a new instance of SearchBeanController
   */
  public SearchBeanController() {
    jmbUserPostsFacade = new JmbUserPostsFacade();
    jmbPostTagsFacade = new JmbPostTagsFacade();
  }
  
  public List<JmbUserPosts> obtenerPosts(){
    List<JmbUserPosts> orderedPosts = new LinkedList<JmbUserPosts>();
    List<JmbUserPosts> userPosts = jmbUserPostsFacade.findAll();
    for (int i = userPosts.size()-1; i >=0; i--) {
      orderedPosts.add(userPosts.get(i));
      
    }
    return orderedPosts;
  }
  
 public List<JmbUserPosts> buscarPosts(){
   List<JmbUserPosts> lstPosts = new LinkedList<JmbUserPosts>();
   List<JmbPostTags> tagsByPost = jmbPostTagsFacade.findAll();
   ArrayList<Integer> postIds = new ArrayList<Integer>();
   for (Iterator<JmbPostTags> it = tagsByPost.iterator(); it.hasNext();) {
     JmbPostTags objTag = it.next();
     if(objTag.getTagName() == null ? postQ == null : objTag.getTagName().equals(postQ)){
       postIds.add(objTag.getTagPostId());
     }
     
   }
   if(postIds.size()>0){
     for (Iterator<Integer> it = postIds.iterator(); it.hasNext();) {
       Integer integer = it.next();
       
       lstPosts.add(jmbUserPostsFacade.find(integer.intValue()));
       
     }
   }
   
   return lstPosts;
 }
 
 

  /**
   * @return the postQ
   */
  public String getPostQ() {
    return postQ;
  }

  /**
   * @param postQ the postQ to set
   */
  public void setPostQ(String postQ) {
    this.postQ = postQ;
  }
  
  
}
